package com.fafu.service.Impl;

import com.fafu.dao.mapper.ManagerMapper;
import com.fafu.dao.mapper.PageMapper;
import com.fafu.model.Manager;
import com.fafu.model.Page;
import com.fafu.pojo.PageExPojo;
import com.fafu.service.PageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import util.Dictionary;
import util.MyMap;
import util.PageTree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageServiceImpl implements PageService {
    @Autowired
    private PageMapper pageMapper;
    @Autowired
    private ManagerMapper managerMapper;
    @Override
    public Map<String, Object> getPageList(Map<String, Object> paramMap) {
        Integer oid = (Integer) paramMap.get("oid");
        Manager manager = managerMapper.selectByPrimaryKey(oid);
        Integer power = manager.getPower();
        List<Page> pageList =  pageMapper.getUrls(new MyMap().put("power",power).toMap());
//        List<PageTree> pageTrees = createTree(pageList);
        List<PageExPojo> reList = new ArrayList<>();
        for(Page data:pageList){
            PageExPojo pageExPojo = new PageExPojo();
            BeanUtils.copyProperties(data,pageExPojo);
            pageExPojo.setElementId("n"+data.getId()+"_"+data.getRegion());
            reList.add(pageExPojo);
        }
        return new MyMap().put("data",reList).toMap();
    }
    private List<PageTree> createTree(List<Page> pageList){
        List<PageTree> pageForest = new ArrayList<>();//头部树
        Map<Integer,PageTree> nodeMap = new HashMap<>();//字典
        for(Page data:pageList)
            if(data.getParentId().equals(Dictionary.TREE.TOP)){  //根节点
                PageTree node = new PageTree();
                BeanUtils.copyProperties(data,node);
                node.setElementId("n"+node.getId()+"_"+node.getRegion()); //dom中的id
                node.setElementParentId("n_"+node.getRegion());           //dom中的父id
                nodeMap.put(node.getId(),node);
                pageForest.add(node);
            }else{      //非根节点
                PageTree parent = nodeMap.get(data.getParentId());
                if(parent.getChildNode() == null)
                    parent.setChildNode(new ArrayList<PageTree>());
                PageTree node = new PageTree();
                BeanUtils.copyProperties(data,node);
                node.setElementId("n"+node.getId()+"_"+node.getRegion());
                node.setElementParentId(parent.getElementId());
                parent.getChildNode().add(node);
                nodeMap.put(data.getId(),node);
            }
        return pageForest;
    }


}
